using System.Collections.Generic;
using System.Data;
using System.Linq;
using MongoDB;
using SkynetMongoDBAccess.Converter;

namespace SkynetMongoDBAccess;

public class MongoKeyValueDB : MongoAbstractDB
{
	private MongoCollection<Document> _mongoCollection;

	public MongoCollection<Document> GetMongoCollcetion
	{
		get
		{
			if (_mongoCollection == null)
			{
				_mongoCollection = base.GetDataBase.GetCollection<Document>(base.CollectionName) as MongoCollection<Document>;
			}
			return _mongoCollection;
		}
	}

	public MongoKeyValueDB(string conString)
		: base(conString)
	{
	}

	public MongoKeyValueDB(string connection, string collection, long cacheLength)
		: base(connection, cacheLength)
	{
		base.CollectionName = collection;
	}

	public void Open(string dbname, string collname)
	{
		Open(dbname);
		if (!string.IsNullOrEmpty(collname) && base.CollectionName != collname)
		{
			base.CollectionName = collname;
			_mongoCollection = base.GetDataBase.GetCollection<Document>(collname) as MongoCollection<Document>;
		}
	}

	public void Insert(Document document)
	{
		GetMongoCollcetion.Insert(document);
	}

	public void Insert(List<Document> list)
	{
		GetMongoCollcetion.Insert(list);
	}

	public void Save(Document document)
	{
		GetMongoCollcetion.Save(document, safemode: false);
	}

	public void Delete(Document document)
	{
		GetMongoCollcetion.Remove(document);
	}

	public void Modify(Document document, Document filter)
	{
		GetMongoCollcetion.FindAndModify(document, filter);
	}

	public void DeleteAll()
	{
		GetMongoCollcetion.Remove(new Document());
	}

	public IEnumerable<Document> FindAll()
	{
		return GetMongoCollcetion.FindAll().Documents;
	}

	public DataSet? FindAllTable()
	{
		return FindAll().ConvertToDataSet();
	}

	public DataSet? FindAllTable(Document document)
	{
		return Find(document).ConvertToDataSet();
	}

	public DataSet FindAllTable(Document document, int index, int count, out int maxCount)
	{
		ICursor<Document> cursor = GetMongoCollcetion.Find(document);
		maxCount = cursor.Documents.Count();
		return GetMongoCollcetion.Find(document).Skip(index).Limit(count)
			.Documents.ToList().ConvertToDataSet();
	}

	public DataSet? FindAllTable(int index, int count, out int maxCount)
	{
		IQueryable<Document> source = GetMongoCollcetion.Linq();
		maxCount = source.Count();
		return source.Skip(index).Take(count).ToList()
			.ConvertToDataSet();
	}

	public IEnumerable<Document> Find(Document document)
	{
		return GetMongoCollcetion.Find(document).Documents;
	}

	public Document FindOne(Document document)
	{
		return GetMongoCollcetion.FindOne(document);
	}
}
